from django.db.models import Q
from rest_framework import serializers
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from goods.models import SKUImage, SKU
from meiduo_admin.serializers.skus import SkusImagesSerializer, SkusSimpleSerializer, SkusSerializer


class SkusImagesView(ModelViewSet):
    permission_classes = [IsAdminUser]
    serializer_class = SkusImagesSerializer
    queryset = SKUImage.objects.all()
    pagination_class = None
    lookup_value_regex = '\d+'


class SkusSimpleView(ListAPIView):
    permission_classes = [IsAdminUser]
    pagination_class = None
    serializer_class = SkusSimpleSerializer
    queryset = SKU.objects.all()
    lookup_value_regex = '\d+'


class SkusView(ModelViewSet):
    permission_classes = [IsAdminUser]
    serializer_class = SkusSerializer
    lookup_value_regex = '\d+'

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            queryset = SKU.objects.filter(Q(name__contains=keyword)
                                          | Q(caption__contains=keyword))
        else:
            queryset = SKU.objects.all()

        return queryset
